/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact z_huatai@qq.com
 *  
 */
package org.zfes.snowy.base.web.resolver;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.zfes.snowy.base.web.annos.ListParam;
import org.zfes.snowy.core.util.ZStrUtil;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
 * 
 * @author zhaohuatai
 * 低版本：jquery 提交数据组 ：id :1&id:2没有问题<br>
 * 解决：高版本 jquery ajax 提交数组时：id[]:1&id[]:2.... 问题，<br>
 * (带有 [] 导致 springmvc无法解析)<br>
 *支持数组参数形式：id：1 id：2;  id[]:1 id[]:2 ;  id :1&id:2
 */
public  class ArrayListResolver implements HandlerMethodArgumentResolver {

	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(ListParam.class);
	}
	
	public Object resolveArgument(MethodParameter parameter,   ModelAndViewContainer mavContainer, NativeWebRequest webRequest,  
	        WebDataBinderFactory binderFactory) throws Exception {
		
		if(parameter.hasParameterAnnotation(ListParam.class)){
			
			ListParam ListParam=parameter.getParameterAnnotation(ListParam.class);
			Class<?> requiredType=ListParam.value();
			
			String methodParamName=parameter.getParameterName();
			
			Map<String, String[]>  psams=webRequest.getParameterMap();
    		//----------------定位参数---------------------
    		String[] values=psams.get(methodParamName);
			if(values==null||values.length==0){
				values=psams.get(methodParamName+"[]");
			}
			//-----------------定位参数--------------------
			if(values!=null&&values.length>0){
				return Stream.of(values).map(v -> ZStrUtil.convert(requiredType,v)).collect(Collectors.toList());
			}
		}
		return null;
	}
}




